package com.cap.bts.crmdp.dealer.masterinfo.utils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.cap.bts.framework.common.exception.AppException;

public class MasterInfoUtils {

    private static final Logger LOGGER = Logger.getLogger(MasterInfoUtils.class);

    /**
     * @Date : Nov 10, 2015
     */
    private MasterInfoUtils() {
        super();
    }

    /**
     * 解析CSV文件
     * 
     * @param file
     *            csv文件(路径+文件)
     * @return
     */
    @SuppressWarnings("resource")
    public static List<String> analyzeCsv(File file) throws AppException {
        List<String> dataList = new ArrayList<String>();
        BufferedReader br = null;
        String line = "";
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            while ((line = br.readLine()) != null) {
                dataList.add(line);
            }
        } catch (UnsupportedEncodingException e) {
            throw new AppException("analyzeCsv", e);
        } catch (IOException e) {
            throw new AppException("analyzeCsv", e);
        }finally{
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    LOGGER.error("流关闭错误", e);
                    br=null;
                }
            }
        }

        return dataList;
    }

    /**
     * 组合CSV文件的内容
     * 
     * @param dataList
     *            CSV文件的内容
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static List<Map<String, Object>> combinationList(List<String> dataList) {

        Map<String, Object> dataMap = null;

        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();

        List list = new ArrayList();
        int num = 0;
        for (Iterator iterator = dataList.iterator(); iterator.hasNext();) {
            String data = (String) iterator.next();
            dataMap = new HashMap<String, Object>();

            String[] dataStrings = data.split("\\^");
            if (num == 0) {
                for (int i = 0; i < dataStrings.length; i++) {
                    list.add(i, dataStrings[i].trim());
                }
            } else {
                for (int i = 0; i < dataStrings.length; i++) {
                    dataMap.put((String) list.get(i), dataStrings[i]);
                }
                resultList.add(dataMap);
            }
            num++;
        }
        return resultList;
    }

    /**
     * 将一个 Map 对象转化为一个 JavaBean
     * 
     * @param type
     *            要转化的类型
     * @param map
     *            包含属性值的 map
     * @return 转化出来的 JavaBean 对象
     * @throws IntrospectionException
     *             如果分析类属性失败
     * @throws IllegalAccessException
     *             如果实例化 JavaBean 失败
     * @throws InstantiationException
     *             如果实例化 JavaBean 失败
     * @throws InvocationTargetException
     *             如果调用属性的 setter 方法失败
     */
    public static Object convertMap(Class<?> type, Map<String, Object> map) throws AppException {
        // 获取类属性
        BeanInfo beanInfo;

        // 创建 JavaBean 对象
        Object obj;
        try {
            beanInfo = Introspector.getBeanInfo(type);
            obj = type.newInstance();
        } catch (InstantiationException e1) {
            throw new AppException("convertMap", e1);
        } catch (IllegalAccessException e1) {
            throw new AppException("convertMap", e1);
        } catch (IntrospectionException e1) {
            throw new AppException("convertMap", e1);
        }

        // 给 JavaBean 对象的属性赋值
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        // System.out.println("Map:" + map)
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();

            if (map.containsKey(propertyName)) {
                // 下面一句可以 try 起来，这样当一个属性赋值失败的时候就不会影响其他属性赋值
                Object value = map.get(propertyName);
                // System.out.println("propertyName:" + propertyName + "的值为：" +
                // value)
                Object[] args = new Object[1];
                args[0] = value;

                try {
                    descriptor.getWriteMethod().invoke(obj, args);
                } catch (Exception e) {
                    LOGGER.error(e);
                }
            }
        }
        return obj;
    }
}
